﻿using Company.Core.IOC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Company.UI.Controls
{
    /// <summary>
    /// PopupBox.xaml 的交互逻辑
    /// </summary>
    public partial class PopupBox : Popup
    {
        public PopupBox()
        {
            InitializeComponent();
        }

        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.Register("Message", typeof(string), typeof(PopupBox), new PropertyMetadata(string.Empty));

        public new double Opacity
        {
            get { return (double)GetValue(OpacityProperty); }
            set { SetValue(OpacityProperty, value); }
        }

        public new static readonly DependencyProperty OpacityProperty =
            DependencyProperty.Register("Opacity", typeof(double), typeof(PopupBox), new PropertyMetadata(0.6));


        private DispatcherTimer _timer = new DispatcherTimer();
        private void TimerStart(int seconds)
        {
            _timer.Interval = TimeSpan.FromSeconds(seconds);
            _timer.Tick -= _timer_Tick;
            _timer.Tick += _timer_Tick;
            _timer.Start();
        }

        private void TimerStop()
        {
            _timer.Stop();
            _timer.Tick -= _timer_Tick;
        }

        public static void Show(string message, Window owner = null, int seconds = 2)
        {
            owner = owner ?? System.Windows.Application.Current.MainWindow;
            var box = new PopupBox();
            box.Message = message;
            box.PlacementTarget = owner;
            box.Placement = PlacementMode.Center;
            box.StaysOpen = true;
            box.AllowsTransparency = true;
            box.IsOpen = true;
            box.TimerStart(seconds);
        }

        private void _timer_Tick(object? sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                await PrismProvider.Dispatcher.Invoke(async () =>
                {
                    for (int i = 0; i < 50; i++)
                    {
                        await Task.Delay(1);
                        Opacity -= 0.01;
                    }

                    this.IsOpen = false;
                    this.TimerStop();
                });
            });
        }
    }
}
